package com.zbvc.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zbvc.dao.AdminDao;
import com.zbvc.dao.impl.AdminDaoImpl;
import com.zbvc.entity.Admin;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "login", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 防止中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		// 接受用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username="+username + "====pwd====" +password );
		
		// 从数据库查询该用户是否存在
		AdminDao adminDao = new AdminDaoImpl();
		Admin admin = adminDao.selectByNameAndPwd(username, password);
		HttpSession session = request.getSession();  // 获取session对象
		
		if(admin != null) {
			session.setAttribute("admin", admin); // 将当前登录用户信息保存到session
			// 设置session失效时间  
			session.setMaxInactiveInterval(60*60);
			// 登录成功
			System.out.println("登录成功");
			// 判断该用户是管理员还是读者
			if(admin.getStatus() == 0) {
				// 管理员
				response.sendRedirect("/bookManager/admin/admin.jsp");
			}else {
				//读者
				response.sendRedirect("/bookManager/user/user.jsp");
			}
		}else {
			session.setAttribute("errorMsg", "密码或用户名错误");
			System.out.println("登录失败");
			//跳转到登录页面
			response.sendRedirect("/bookManager/login.jsp");
		}
	}

}
